<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>更换头像</span>
    </div>
    <div class="img-box">
      <!-- 图片，用来展示用户选择的头像 -->
      <img v-if="avatar" :src="avatar" alt="" />
      <img v-else src="../../../assets/images/avatar.jpg" alt="" />

      <!-- 按钮区域 -->
      <div class="btn-box">
        <input
          @change="fileChangeHandler"
          ref="fileInp"
          accept="image/*"
          type="file"
          style="display:none"
        />
        <el-button
          @click="$refs.fileInp.click()"
          type="primary"
          icon="el-icon-plus"
          >选择图片</el-button
        >
        <el-button
          @click="updateAvatarHandler"
          type="success"
          icon="el-icon-upload"
          :disabled="!avatar"
          >上传头像</el-button
        >
      </div>
    </div>
  </el-card>
</template>

<script>
export default {
  name: 'UserAvatar',
  data () {
    return {
      avatar: ''
    }
  },
  methods: {
    fileChangeHandler (e) {
      if (e.target.files.length === 0) {
        // 用户没有选择图片
        this.avatar = ''
      } else {
        const fr = new FileReader()
        fr.readAsDataURL(e.target.files[0])
        // 绑定事件,必须要使用箭头函数,因为要访问 data 中的数据
        fr.onload = e => {
          this.avatar = e.target.result
        }
      }
    },
    async updateAvatarHandler () {
      // 发请求更新头像
      const { data: res } = await this.$http.patch('/my/update/avatar', {
        avatar: this.avatar
      })
      // 根据状态提示用户
      if (res.code !== 0) return this.$message.error(res.message)
      this.$message.success(res.message)
      // 更新用户信息
      this.$store.dispatch('user/getUserInfo')
    }
  }
}
</script>

<style lang="less" scoped>
.btn-box {
  margin-top: 10px;
}
.preview {
  object-fit: cover;
}
.img-box img {
  width: 350px;
  // height: 350px;
}
</style>
